<template>
  <div>
    <!-- 查询 -->
    <a-row>
      <a-col :span="6">
        <a-form-item label="用户名称" :wrapper-col="{ span: 16 }" name="name">
          <a-select
            v-model:value="queryData.userId"
            show-search
            placeholder="请输入用户名称"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="userData"
            @search="handleSearchUser"
          ></a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6" v-if="isDctor">
        <a-form-item label="医生名称" :wrapper-col="{ span: 16 }" name="name">
          <a-select
            v-model:value="queryData.doctorId"
            show-search
            placeholder="请输入医生名称"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="userData2"
            @search="handleSearchDoctor"
          ></a-select>
        </a-form-item>
      </a-col>

      <a-col :span="6">
        <a-form-item label="服务状态" name="communityId">
          <a-select
            placeholder="请选择服务状态"
            ref="select"
            v-model:value="queryData.status"
          >
            <a-select-option value="1">已预约</a-select-option>
            <a-select-option value="3">已过期</a-select-option>
            <a-select-option value="4">待支付</a-select-option>
            <a-select-option value="5">支付失败</a-select-option>
            <a-select-option value="6">就诊成功</a-select-option>
            >
          </a-select>
        </a-form-item>
      </a-col>

      <a-col v-if="!isDctor" :span="6"> </a-col>
      <a-col :span="6">
        <a-button @click="reset" style="margin-left: 20px">重置</a-button>
        <a-button
          @click="selectInfo"
          style="margin: 0 20px; background-color: #6a2c70"
          type="primary"
          >查询</a-button
        >
      </a-col>
      <a-col :span="12">
        <a-form-item label="预约时间">
          <a-range-picker
            :value="hackValue || value"
            :disabled-date="disabledDate"
            @change="onChange"
            @openChange="onOpenChange"
            @calendarChange="onCalendarChange"
          />
        </a-form-item>
      </a-col>
    </a-row>

    <a-table
      tableLayout="fixed"
      :loading="isloading"
      :pagination="pagination"
      :columns="columns"
      @change="handleTableChange"
      :data-source="reserations.data"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'appointmentDate'">
          {{ stringSlicing(record.appointmentDate) }}
          {{ record.appointmentTime == 'morning' ? '上午' : '下午' }}
        </template>
        <template v-if="column.key === 'status'">
          <a-tag color="blue" v-if="record.status == 1">已预约</a-tag>
          <a-tag color="green" v-if="record.status == 2">就诊中</a-tag>
          <a-tag color="red" v-if="record.status == 3">已过期</a-tag>

          <a-tag color="cyan" v-if="record.status == 4">待支付</a-tag>
          <a-tag color="pink" v-if="record.status == 5"> 支付失败 </a-tag>
          <a-tag color="green" v-if="record.status == 6"> 就诊成功 </a-tag>
        </template>

        <template v-if="column.key === 'action'">
          <a-button
            @click="showDateils(record)"
            type="primary"
            style="margin-right: 20px; background-color: #f5b017"
            >详细</a-button
          >
        </template>
      </template>
    </a-table>

    <a-drawer
      v-model:open="open"
      class="custom-class"
      root-class-name="root-class-name"
      title="详情展示"
      placement="right"
      width="60%"
      :maskClosable="false"
    >
      <ReservationDrawer v-if="open" :info="proprInfo" />
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import ReservationDrawer from './ReservationDrawer.vue'
import { ref, reactive, onMounted } from 'vue'
import { columns } from './columns'
import { PaginationModel } from '@/api/config/Model'
import { apiAllList } from '@/api/Community/api'
import { apiQueryList } from '@/api/User/api'
import { apiGetPageList } from '@/api/Service/api'
// import { queryDataModel } from '@/api/Service/model'
import { message } from 'ant-design-vue'
import { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs]
const userInfo = ref<any>({})
const isDctor = ref<boolean>(true)
const userData: any = ref([])
const userData2: any = ref([])
const queryData = reactive<any>({
  userId: null,
  communityId: null,
  doctorId: null,
  status: null,
  page: 1,
  pageSize: 10,
  startDate: null,
  endDate: null,
})
const dates = ref<RangeValue>()
const value = ref<RangeValue | null>()
const hackValue = ref<RangeValue>()

const disabledDate = (current: Dayjs) => {
  if (!dates.value || (dates.value as any).length === 0) {
    return false
  }
  const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 29
  const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 30
  return tooEarly || tooLate
}

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any
    hackValue.value = [] as any
  } else {
    hackValue.value = undefined
  }
}

const onChange = (val: any) => {
  value.value = val
  let startMonth = val[0].$M + 1 < 10 ? '0' + (val[0].$M + 1) : val[0].$M + 1
  let endMonth = val[1].$M + 1 < 10 ? '0' + (val[1].$M + 1) : val[1].$M + 1
  let startDay = val[0].$D + 1 < 10 ? '0' + val[0].$D : val[0].$D
  let endDay = val[1].$D + 1 < 10 ? '0' + val[1].$D + 1 : val[1].$D

  queryData.startDate = `${val[0].$y}-${startMonth}-${startDay}`
  queryData.endDate = `${val[1].$y}-${endMonth}-${endDay}`
}

const onCalendarChange = (val: RangeValue) => {
  dates.value = val
}

const proprInfo = reactive({
  userId: null,
  doctorId: null,
  communityId: null,
  reservationId: null,
})
const open = ref<boolean>(false)
const pagination = ref<PaginationModel>({
  current: 1,
  total: 100,
  pageSize: 10, //每页中显示10条数据
  pageSizeOptions: ['10', '20', '30'],
})

const isloading = ref<boolean>(false)
//预约列表
const reserations = reactive({
  data: [],
})
const communityData: any = ref([])
const currentValue: any = ref()
const currentValue1: any = ref()
let timeout2: any = ref(null)
let timeout: any = ref(null)

const reset = () => {
  value.value = null
  queryData.startDate = null
  queryData.endDate = null
  queryData.userId = null
  queryData.status = null
  if (userInfo.value.empId == 0) {
    queryData.doctorId = null
  }
  if (userInfo.value.type == 1) {
    queryData.doctorId = null
  }
  getList()
}

const showDateils = (item: any) => {
  open.value = true
  proprInfo.userId = item.userId
  proprInfo.doctorId = item.doctorId
  proprInfo.communityId = item.communityId
  proprInfo.reservationId = item.reservationId
}

const stringSlicing = (str: string) => {
  return str.split('T')[0]
}
const handleSearchDoctor = (value: any) => {
  if (timeout.value) {
    clearTimeout(timeout.value)
    timeout.value = null
  }
  timeout.value = setTimeout(async () => {
    currentValue1.value = value
    //搜索用户
    let res = await apiQueryList({
      name: value,
      type: 3,
    })

    userData2.value = res.data.map((ele: any) => {
      return {
        label: ele.name,
        value: ele.empId,
        ...ele,
      }
    })
  }, 300)
}

const handleSearchUser = (value: any) => {
  if (timeout2.value) {
    clearTimeout(timeout2.value)
    timeout2.value = null
  }
  timeout2.value = setTimeout(async () => {
    currentValue.value = value
    //搜索用户
    let res = await apiQueryList({
      name: value,
      type: 2,
    })

    userData.value = res.data.map((ele: any) => {
      return {
        label: ele.name,
        value: ele.empId,
        ...ele,
      }
    })
  }, 300)
}

//查询信息
const selectInfo = () => {
  getList()
}

//获取列表
const getList = async () => {
  isloading.value = true
  try {
    let res: any = await apiGetPageList(queryData)
    reserations.data = res.data.records
    pagination.value.current = res.data.current
    pagination.value.pageSize = res.data.size
    pagination.value.total = res.data.total
  } catch (error) {
    message.error('获取列表失败')
  }
  isloading.value = false
}
// 分页改变
const handleTableChange = (page: any) => {
  pagination.value.current = page.current
  pagination.value.pageSize = page.pageSize
  queryData.page = page.current
  queryData.pageSize = page.pageSize
  getList()
}

onMounted(async () => {
  //获取所有社区列表
  let res = await apiAllList()
  communityData.value = res.data.map((ele: any) => {
    return {
      label: ele.communityName,
      value: ele.communityId,
      ...ele,
    }
  })
  userInfo.value = JSON.parse(localStorage.getItem('employeeInfo') || '')
  //对d进行固定
  if (userInfo.value.empId != 0) {
    queryData.communityId = userInfo.value.communityId
  }

  if (userInfo.value.type == 3) {
    queryData.doctorId = userInfo.value.empId
    isDctor.value = false
  }

  getList()
})
</script>

<style lang="less" scoped></style>
